<template>
  <view class="machine">
    <view class="video">
      <video src="https://video.699pic.com/videos/86/10/49/a_680077796464517448610494134_10s.mp4"></video>
    </view>
    <view class="cut-off"></view>
    <view class="dashboard">
      <view class="dashboard-top">
        <view class="dashboard-top-left">
          <image src="/@/static/images/jiansu.png" @click="reduceChartValue"></image>
        </view>
        <view class="dashboard-top-center">
          <view style="width:100%;height:100%">
            <l-echart ref="chartRef" @finished="init"></l-echart>
          </view>
          <!--          <view id="echarts" style="width:100%;height:100%"></view>-->
        </view>
        <view class="dashboard-top-right">
          <image src="/@/static/images/jiasu.png" @click="increaseChartValue"></image>
        </view>
      </view>
      <view class="dashboard-bottom">{{ chartOptionRef.series[0].data[0].value }} m/min</view>
    </view>
    <view class="cut-off"></view>

    <view class="main">
      <template v-for="(item,index) in configListRef" :key="item.key">
        <view class="main-item" v-if="item.type===1">
          <view class="main-item-top">
            <view class="main-item-top-title">{{ item.title }}</view>
          </view>
          <view class="main-item-bottom">
            <view class="main-item-bottom-item" @click="onChangeItemActive(index,item1)"
                  :class="item.value===item1.value?'main-item-bottom-item-active':''"
                  v-for="(item1,index1) in item.list" :key="item1.value"
                  :style="{width:(100/item.list.length).toFixed(2)+'%'}">
              {{ item1.label }}
            </view>
          </view>
        </view>
        <view class="main-item-one" v-if="item.type===2">
          <view class="main-item-one-left">
            <view class="main-item-one-left-icon">
              <image :src="item.icon"></image>
            </view>
            <view class="main-item-one-label">{{ item.title }}</view>
          </view>
          <view class="main-item-one-right">
            <switch :checked="item.value" color="#2F6BFF" @change="onChangeSwitch($event,index)"
                    style="transform:scale(0.8)"/>
          </view>
        </view>
      </template>
    </view>

  </view>
</template>

<script setup>
import * as echarts from 'echarts'
import {onHide, onLoad, onShow, onUnload} from "@dcloudio/uni-app";
import {ref} from "vue";
import {cloneDeep} from "lodash"

import rangeExtender from '/src/static/images/fuzengqi.png'
import light from '/src/static/images/chedeng.png'
import vacuuming from '/src/static/images/xicheng-2.png'
import adaptive from '/src/static/images/zishiying.png'
import initialStandard from '/src/static/images/chushijiaozhun.png'
import {getLocalStorage, showMessage} from "/@/utils/util";
import {STORAGE_KEY} from "/@/config/constant";
import * as iHome from "/@/api/iHome";

const chartRef = ref(null)
const configListRef = ref([
  {
    title: "模式",
    key: 'mode',
    type: 1,
    value: 1,
    list: [
      {label: '正常行驶', value: 1},
      {label: '原地转向', value: 2},
      {label: '横向行驶', value: 3},
      {label: '斜行模式', value: 4},
    ]
  },
  {
    title: "挡位",
    key: 'gear',
    type: 1,
    value: 1,
    list: [
      {label: 'P', value: 1},
      {label: 'R', value: 2},
      {label: 'N', value: 3},
      {label: 'D', value: 4},
    ]
  },
  {
    title: "增程器",
    key: 'rangeExtender',
    type: 2,
    icon: rangeExtender,
    value: false
  },
  {
    title: "车灯",
    key: 'light',
    type: 2,
    icon: light,
    value: false
  },
  {
    title: "吸尘",
    key: 'vacuuming',
    type: 2,
    icon: vacuuming,
    value: false
  },
  {
    title: "滚刷速度",
    key: 'rollerBrushSpeed',
    type: 1,
    value: 1,
    list: [
      {label: '0', value: 1},
      {label: '1', value: 2},
      {label: '2', value: 3},
      {label: '3', value: 4},
    ]
  },
  {
    title: "自适应",
    key: 'adaptive',
    type: 2,
    icon: adaptive,
    value: false
  },
  {
    title: "初始对准",
    key: 'initialStandard',
    type: 2,
    icon: initialStandard,
    value: false
  },
  {
    title: "位置",
    key: 'address',
    type: 1,
    value: 1,
    list: [
      {label: '上回位', value: 1},
      {label: '停止', value: 2},
      {label: '下回位', value: 3},
    ]
  },
])
const chartOptionRef = ref({
  series: [
    {
      type: 'gauge',
      radius: '150%',
      center: ['50%', '80%'],
      startAngle: 180,
      endAngle: 0,
      min: 0,
      max: 100,
      splitNumber: 10,
      itemStyle: {
        color: '#2f6bff',
        shadowColor: 'rgba(0,138,255,0.45)',
        shadowBlur: 4,
        shadowOffsetX: 2,
        shadowOffsetY: 2
      },
      progress: {
        show: true,
        roundCap: true,
        width: 8
      },
      pointer: {
        icon: 'path://M2090.36389,615.30999 L2090.36389,615.30999 C2091.48372,615.30999 2092.40383,616.194028 2092.44859,617.312956 L2096.90698,728.755929 C2097.05155,732.369577 2094.2393,735.416212 2090.62566,735.56078 C2090.53845,735.564269 2090.45117,735.566014 2090.36389,735.566014 L2090.36389,735.566014 C2086.74736,735.566014 2083.81557,732.63423 2083.81557,729.017692 C2083.81557,728.930412 2083.81732,728.84314 2083.82081,728.755929 L2088.2792,617.312956 C2088.32396,616.194028 2089.24407,615.30999 2090.36389,615.30999 Z',
        length: '70%',
        width: 6,
        offsetCenter: [0, '5%']
      },
      axisLine: {
        roundCap: true,
        lineStyle: {
          width: 6
        }
      },
      axisTick: {
        splitNumber: 2,
        lineStyle: {
          width: 2,
          color: '#999'
        },
      },
      splitLine: {
        distance: 4,
        length: 6,
        lineStyle: {
          width: 2,
          color: '#999'
        }
      },
      axisLabel: {
        distance: 14,
        color: '#999',
        fontSize: 10,
      },
      title: {
        show: false
      },
      detail: {
        show: false,
      },
      data: [
        {
          value: 50
        }
      ]
    }
  ]
})
const deviceStateRef = ref({
  drivingMode: '',
  speed: '',
  gear: '',
  gearName: '',
  vehicleMode: '',
  brushSpeed: '',
  brushMode: '',
  chassisMode: '',
  positionMode: ''
})
let refreshInterval = null;

const init = () => {
  chartRef.value.init(echarts, (chart) => {
    chart.setOption(getChartOption())

    setTimeout(() => {
      chart.setOption(getChartOption())
    }, 300)
  })
}

const onChangeSwitch = (e, e1) => {
  let list = cloneDeep(configListRef.value)
  let tempType = list[e1].key
  console.log(tempType, e, e1)
  let robotControlReq = JSON.parse(getLocalStorage(STORAGE_KEY.dropdownCurrentDeviceId))
  if (!robotControlReq) {
    showMessage('设备Mac地址获取失败!')
    return
  }
  if (tempType === 'rangeExtender') { // 增程器
    robotControlReq.rangeExtender = e.detail.value ? '1' : '0'
    iHome.rangeExtendAdjust(robotControlReq).then(res => {
      console.log('增程器调整响应', robotControlReq, res)
      if (!res || res.code !== 200) {
        showMessage('增程器调整失败!')
        return
      }
    })
  } else if (tempType === 'light') { // 车灯
    robotControlReq.carLight = e.detail.value ? '1' : '0'
    iHome.carLightAdjust(robotControlReq).then(res => {
      console.log('车灯调整响应', robotControlReq, res)
      if (!res || res.code !== 200) {
        showMessage('车灯调整失败!')
        return
      }
    })
  } else if (tempType === 'vacuuming') { // 吸尘
    robotControlReq.dustAbsorption = e.detail.value ? '1' : '0'
    robotControlReq.cleanSpeed = '20'
    iHome.dustAbsorptionAdjust(robotControlReq).then(res => {
      console.log('吸尘调整响应', robotControlReq, res)
      if (!res || res.code !== 200) {
        showMessage('吸尘调整失败!')
        return
      }
    })
  } else if (tempType === 'adaptive') { // 自适应
    robotControlReq.selfAdaptive = e.detail.value ? '1' : '0'
    iHome.selfAdaptiveAdjust(robotControlReq).then(res => {
      console.log('自适应调整响应', robotControlReq, res)
      if (!res || res.code !== 200) {
        showMessage('自适应调整失败!')
        return
      }
    })
  } else if (tempType === 'initialStandard') { // 初始对准
    robotControlReq.initAlignment = e.detail.value ? '1' : '0'
    iHome.initAlignmentAdjust(robotControlReq).then(res => {
      console.log('初始对准调整响应', robotControlReq, res)
      if (!res || res.code !== 200) {
        showMessage('初始对准调整失败!')
        return
      }
    })
  }
  list[e1].value = e.detail.value
  configListRef.value = list
}

const getChartOption = () => {
  return chartOptionRef.value
}

const loadInfo = () => {
  let params = JSON.parse(getLocalStorage(STORAGE_KEY.dropdownCurrentDeviceId))
  if (!params) {
    showMessage('设备Mac地址获取失败!')
    return
  }
  // console.log(params)
  iHome.basicState(params).then(res => {
    if (!res || !res.data
        || !res.data.dataJson
        || !res.data.dataJson.statusData
        || !params.deviceId === res.data.dataJson.macAddress) {
      showMessage('设备状态获取失败!')
      return
    }
    const statusData = res.data.dataJson.statusData;
    const chassis = statusData.chassis;
    const brush = statusData.brush;
    if (chassis) {
      if (chassis.autonomous) {
        deviceStateRef.value.drivingMode = chassis.autonomous
      }
      if (chassis.speeds) {
        deviceStateRef.value.speed = chassis.speeds
      }
      if (chassis.gear) {
        deviceStateRef.value.gearName = chassis.gear
        deviceStateRef.value.gear = extractLetters(chassis.gear)
      }
      if (chassis.vehicleStatus) {
        deviceStateRef.value.vehicleMode = chassis.vehicleStatus
      }
    }
    if (brush) {
      deviceStateRef.value.brushSpeed = getBrushSpeed(brush)
      deviceStateRef.value.brushMode = brush.brushMode
    }
    console.log('onLoad', deviceStateRef.value)
    let speed = parseInt(deviceStateRef.value.speed.replace(/m\/min/, ''))
    updateChartValue(speed)
    const newConfigList = cloneDeep(configListRef.value)

    newConfigList.forEach(category => {
      if (category.key === 'mode') {
        const item1 = category.list.find(item => {
          // console.log(item)
          return item.label === deviceStateRef.value.vehicleMode
        })
        category.value = item1?.value || -1
        // console.log(category)
      } else if (category.key === 'gear') {
        const item1 = category.list.find(item => {
          return (item.label) === extractLetters(deviceStateRef.value.gear)
        })
        category.value = item1?.value || -1
        // console.log(category)
      } else if (category.key === 'rangeExtender') {
        //todo
      } else if (category.key === 'light') {
        //todo
      } else if (category.key === 'vacuuming') {
        if (deviceStateRef.value.brushMode === "开" || deviceStateRef.value.brushMode === "1") {
          category.value = true;
        }
      } else if (category.key === 'rollerBrushSpeed') {
        const item1 = category.list.find(item => {
          // console.log(item)
          return item.label === deviceStateRef.value.brushSpeed
        })
        category.value = item1?.value || -1
        // console.log(category)
      } else if (category.key === 'adaptive') {
        //todo
      } else if (category.key === 'initialStandard') {
        //todo
      } else if (category.key === 'address') {
        //todo
      }
    });
    configListRef.value = newConfigList;
  })
}

const extractLetters = (str) => {
  if (typeof (str) !== 'string') return '';
  return str.replace(/[^a-zA-Z]/g, '');
};


const getBrushSpeed = (brush) => {
  let brushSpeed = Number((brush)?.brushSpeed) || 0; // 强制转为数字，默认为 0
  let brushSpeedLevel = '';
  if (brushSpeed === 0) {
    brushSpeedLevel = '0';
  } else if (brushSpeed > 0 && brushSpeed <= 85) {
    brushSpeedLevel = '1';
  } else if (brushSpeed >= 86 && brushSpeed <= 170) {
    brushSpeedLevel = '2';
  } else if (brushSpeed > 170) {
    brushSpeedLevel = '3';
  }
  return brushSpeedLevel;
}

const updateChartValue = (speed, min = 0, max = 100) => {
  if (typeof (speed) !== "number" || speed < 0 || chartOptionRef.value.series[0].data[0].value === speed) {
    return
  }
  chartOptionRef.value.series[0].data[0].value = speed
  if (speed > max || speed < min || (min !== chartOptionRef.value.series[0].min && max !== chartOptionRef.value.series[0].max)) {
    chartOptionRef.value.series[0].min = speed < min ? speed : min
    chartOptionRef.value.series[0].max = speed > max ? speed : max
  }
  chartRef.value.init(echarts, (chart) => {
    chart.setOption(chartOptionRef.value)
  })
};

const increaseChartValue = () => {
  let robotControlReq = JSON.parse(getLocalStorage(STORAGE_KEY.dropdownCurrentDeviceId))
  if (!robotControlReq) {
    showMessage('设备Mac地址获取失败!')
    return
  }
  if (chartRef.value) {
    const currentValue = chartOptionRef.value.series[0].data[0].value || 0;
    let speed = (currentValue + 5) > 100 ? 100 : currentValue + 5
    robotControlReq.carSpeed = speed
    iHome.carSpeedAdjust(robotControlReq).then(res => {
      console.log('加速响应', robotControlReq, res)
      if (!res || res.code !== 200) {
        showMessage('加速调整失败!')
        return
      } else {
        updateChartValue(speed);
      }
    })
  }
};

const reduceChartValue = () => {
  let robotControlReq = JSON.parse(getLocalStorage(STORAGE_KEY.dropdownCurrentDeviceId))
  if (!robotControlReq) {
    showMessage('设备Mac地址获取失败!')
    return
  }
  if (chartRef.value) {
    const currentValue = chartOptionRef.value.series[0].data[0].value || 0;
    let speed = (currentValue > 5) ? (currentValue - 5) : 0
    robotControlReq.carSpeed = speed
    iHome.carSpeedAdjust(robotControlReq).then(res => {
      console.log('减速响应', robotControlReq, res)
      if (!res || res.code !== 200) {
        showMessage('减速调整失败!')
        return
      } else {
        updateChartValue(speed);
      }
    })
  }
};

const onChangeItemActive = (e, e1) => {
  let list = cloneDeep(configListRef.value)
  let tempType = list[e].key
  console.log(tempType, e, e1)
  let robotControlReq = JSON.parse(getLocalStorage(STORAGE_KEY.dropdownCurrentDeviceId))
  if (!robotControlReq) {
    showMessage('设备Mac地址获取失败!')
    return
  }
  if (tempType === 'mode') { // 模式
    if (deviceStateRef.value.chassisMode !== e1.label) {
      console.log('模式', deviceStateRef.value)
      if (e1.value === 1) {
        robotControlReq.chassisMode = '10'
      } else if (e1.value === 2) {
        robotControlReq.chassisMode = '11'
      } else if (e1.value === 3) {
        robotControlReq.chassisMode = '12'
      } else if (e1.value === 4) {
        robotControlReq.chassisMode = '13'
      }
      iHome.chassisModeAdjust(robotControlReq).then(res => {
        console.log('模式修改响应', robotControlReq, res)
        if (!res || res.code !== 200) {
          showMessage('底盘模式调整失败!')
          return
        } else {
          deviceStateRef.value.chassisMode = e1.label
        }
      })
    }
  } else if (tempType === 'gear') {//档位
    if (extractLetters(deviceStateRef.value.gear) !== e1.label) {
      console.log('档位', deviceStateRef.value)
      if (e1.value === 1) {
        robotControlReq.gearAdjust = '1'
      } else if (e1.value === 2) {
        robotControlReq.gearAdjust = '2'
      } else if (e1.value === 3) {
        robotControlReq.gearAdjust = '0'
      } else if (e1.value === 4) {
        robotControlReq.gearAdjust = '3'
      }
      iHome.gearAdjust(robotControlReq).then(res => {
        console.log('档位修改响应', robotControlReq, res)
        if (!res || res.code !== 200) {
          showMessage('档位调整失败!')
          return
        } else {
          deviceStateRef.value.gear = e1.label
        }
      })
    }
  } else if (tempType === 'rollerBrushSpeed') {//滚刷速度
    if (deviceStateRef.value.brushSpeed !== e1.label) {
      console.log('滚刷速度', deviceStateRef.value)
      if (e1.value === 1) {
        robotControlReq.cleanSpeed = '0'
      } else if (e1.value === 2) {
        robotControlReq.cleanSpeed = '1'
      } else if (e1.value === 3) {
        robotControlReq.cleanSpeed = '2'
      } else if (e1.value === 4) {
        robotControlReq.cleanSpeed = '3'
      }
      iHome.cleanSpeedAdjust(robotControlReq).then(res => {
        console.log('滚刷速度修改响应', robotControlReq, res)
        if (!res || res.code !== 200) {
          showMessage('滚刷速度调整失败!')
          return
        } else {
          deviceStateRef.value.brushSpeed = e1.label
        }
      })
    }
  } else if (tempType === 'address') {//位置
    if (deviceStateRef.value.positionMode !== e1.label) {
      console.log('位置', deviceStateRef.value)
      if (e1.value === 1) {
        robotControlReq.positionMode = '1'
      } else if (e1.value === 2) {
        robotControlReq.positionMode = '2'
      } else if (e1.value === 3) {
        robotControlReq.positionMode = '0'
      }
      iHome.adaptivePositionAdjust(robotControlReq).then(res => {
        console.log('自适应位置修改响应', robotControlReq, res)
        if (!res || res.code !== 200) {
          showMessage('自适应位置调整失败!')
          return
        } else {
          deviceStateRef.value.positionMode = e1.label
        }
      })
    }
  }
  list[e].value = e1.value
  configListRef.value = list
  console.log(configListRef.value)
}

const refreshLoadInfo = () => {
  let params = JSON.parse(getLocalStorage(STORAGE_KEY.dropdownCurrentDeviceId))
  if (!params) {
    showMessage('设备Mac地址获取失败!')
    return
  }
  // console.log(params)
  iHome.basicState(params).then(res => {
    if (!res || !res.data
        || !res.data.dataJson
        || !res.data.dataJson.statusData
        || !params.deviceId === res.data.dataJson.macAddress) {
      // showMessage('设备状态获取失败!')
      return
    }
    const statusData = res.data.dataJson.statusData;
    const chassis = statusData.chassis;
    const brush = statusData.brush;
    if (chassis) {
      if (chassis.autonomous) {
        deviceStateRef.value.drivingMode = chassis.autonomous
      }
      if (chassis.speeds) {
        deviceStateRef.value.speed = chassis.speeds
      }
      if (chassis.gear) {
        deviceStateRef.value.gearName = chassis.gear
        deviceStateRef.value.gear = extractLetters(chassis.gear)
      }
      if (chassis.vehicleStatus) {
        deviceStateRef.value.vehicleMode = chassis.vehicleStatus
      }
    }
    if (brush) {
      deviceStateRef.value.brushSpeed = getBrushSpeed(brush)
      deviceStateRef.value.brushMode = brush.brushMode
    }
    // console.log('onLoad', deviceStateRef.value)
    let speed = parseInt(deviceStateRef.value.speed.replace(/m\/min/, ''))
    updateChartValue(speed)
    const newConfigList = cloneDeep(configListRef.value)

    newConfigList.forEach(category => {
      if (category.key === 'mode') {
        const item1 = category.list.find(item => {
          // console.log(item)
          return item.label === deviceStateRef.value.vehicleMode
        })
        category.value = item1?.value || -1
        // console.log(category)
      } else if (category.key === 'gear') {
        const item1 = category.list.find(item => {
          return (item.label) === extractLetters(deviceStateRef.value.gear)
        })
        category.value = item1?.value || -1
        // console.log(category)
      } else if (category.key === 'rangeExtender') {
        //todo
      } else if (category.key === 'light') {
        //todo
      } else if (category.key === 'vacuuming') {
        if (deviceStateRef.value.brushMode === "开" || deviceStateRef.value.brushMode === "1") {
          category.value = true;
        }
      } else if (category.key === 'rollerBrushSpeed') {
        const item1 = category.list.find(item => {
          // console.log(item)
          return item.label === deviceStateRef.value.brushSpeed
        })
        category.value = item1?.value || -1
        // console.log(category)
      } else if (category.key === 'adaptive') {
        //todo
      } else if (category.key === 'initialStandard') {
        //todo
      } else if (category.key === 'address') {
        //todo
      }
    });
    configListRef.value = newConfigList;
  })
}

onLoad(() => {
  loadInfo()
})

onShow(() => {
  console.log('onShow.setInterval.refreshLoadInfo')
  refreshInterval = setInterval(refreshLoadInfo, 5000);
  console.log(refreshInterval)
});

onHide(() => {
  if (refreshInterval) {
    console.log('onHide.clearInterval.refreshLoadInfo')
    clearInterval(refreshInterval);
    refreshInterval = null;
  }
});

onUnload(() => {
  if (refreshInterval) {
    console.log('onUnload.clearInterval.refreshLoadInfo')
    clearInterval(refreshInterval);
    refreshInterval = null;
  }
});

</script>

<style lang="scss" scoped>
@import "machine";
</style>
